import { useIntersectionObserver, useIntervalFn } from '@vueuse/core'
import { onUnmounted, ref } from 'vue'

// 数据懒加载工具函数
export const useLazyData = (callback: () => void) => {
	const target = ref(null)
	const { stop } = useIntersectionObserver(
		target,
		([{ isIntersecting }]) => {
			if (isIntersecting) {
				callback()
				stop()
			}
		},
		{
			// 只要交叉，立马触发
			threshold: 0,
		}
	)
	return target
}

// 封装倒计时函数
export const useCountDown = (count: number) => {
	const time = ref(0)
	const { pause, resume } = useIntervalFn(
		() => {
			time.value--
			if (time.value === 0) {
				pause()
			}
		},
		1000,
		{ immediate: false }
	)
	// 不能直接使time = ref(count), useCountDown函数只执行一次, 再resume的时候, time会一直递减
	const start = () => {
		time.value = count
		resume()
	}
	// 卸载时销毁
	onUnmounted(() => {
		pause()
	})
	return { time, start }
}
